package com.lt.utils;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 权限申请
 * @author LiuTong
 */
public class PermissionUtils {
    String[] permissions = {Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.KILL_BACKGROUND_PROCESSES,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_CALENDAR};
    private static volatile PermissionUtils instance;
    private int resultCode = 0;
    public static PermissionUtils getInstance(){
        if(instance == null){
            synchronized (PermissionUtils.class){
                if(instance == null){
                    instance = new PermissionUtils();
                }
            }
        }
        return instance;
    }

    /****
     * 检查权限
     * @param activity
     * @param permissions
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public boolean hasPermissions(AppCompatActivity activity, String[] permissions){
        if(permissions == null|| permissions.length <= 0){
            return true;
        }
        for(String permission : permissions){
            if(!hasPermission(activity,permission)){
               return false;
            }
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private  boolean hasPermission(AppCompatActivity activity, String permission){
        if(activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
            return false;
        }
        return true;
    }

    /***
     * 请求权限带回调
     * @param activity
     * @param permissions
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestPermissions(Activity activity, String[] permissions, int code){
        this.resultCode = code;
        activity.requestPermissions(permissions,code);
    }

    /***
     * 申请权限的结果回调，需要在Activity的onRequestPermissionsResult中调用
     * @param activity
     * @param permissions
     * @param permissionResultListen
     */
    public void onPermissionResult(AppCompatActivity activity,
                                   String[] permissions,
                                   PermissionResultListen permissionResultListen){
        if(hasPermissions(activity,permissions)){
            if(permissionResultListen!=null){
                permissionResultListen.onSuccess(resultCode);
            }else {
                permissionResultListen.onFail();
            }
        }

    }
}
